using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Bson;

namespace sgf.server
{
    public static class BsonHelper
    {
        public static byte[] ToBson(Object obj)
        {
            var ms = new MemoryStream();
            using (var writer = new BsonDataWriter(ms))
            {
                var serializer = new JsonSerializer();
                serializer.Serialize(writer, obj);
            }

            return ms.ToArray();
        }

        public static T? FromBson<T>(string bson)
        {
            var data = Convert.FromBase64String(bson);
            using var ms = new MemoryStream(data);
            using var reader = new BsonDataReader(ms);
            var serializer = new JsonSerializer();
            return serializer.Deserialize<T>(reader);
        }

        public static T FromBson<T>(byte[] bson)
        {
            var ms = new MemoryStream(bson);
            using var reader = new BsonDataReader(ms);
            var serializer = new JsonSerializer();
            return serializer.Deserialize<T>(reader);
        }

        public static object FromBson(Type type, byte[] bson)
        {
            var ms = new MemoryStream(bson);
            using var reader = new BsonDataReader(ms);
            var serializer = new JsonSerializer();
            return serializer.Deserialize(reader, type);
        }

        public static object FromBson(Type type, string bson)
        {
            // 将BSON字符串转换为BsonDocument
            var bsonDocument = BsonSerializer.Deserialize<BsonDocument>(bson);

            // 使用BsonSerializer反序列化BsonDocument到指定类型
            var deserializedObject = BsonSerializer.Deserialize(bsonDocument, type);

            return deserializedObject;
        }
    }
}